package cc.ttiot.service.dataCollection.i2c.impl;

import cc.ttiot.service.dataCollection.i2c.I2CCollection;
import com.pi4j.io.i2c.I2CDevice;

import java.io.IOException;

import static cc.ttiot.utils.StringUtils.byte2short;

/**
 * @Description:
 * @Author :
 * @Version :
 * @Date :
 */
public class VibrationCollection implements I2CCollection {
    private static volatile VibrationCollection vibrationCollection;

    private I2CDevice i2CDevice;

    private VibrationCollection() {
        super();
    }

    //双检索单例防止多次初始化
    public static VibrationCollection getInstance(){
        if(vibrationCollection == null){
            synchronized (VibrationCollection.class){
                if(vibrationCollection == null){
                    vibrationCollection = new VibrationCollection();
                }
            }
        }
        return vibrationCollection;
    }

    public I2CDevice getI2CDevice() {
        return i2CDevice;
    }

    public void setI2CDevice(I2CDevice i2CDevice) {
        this.i2CDevice = i2CDevice;
    }

    public double collect() throws IOException {

        byte[] temp = new byte[2];

        i2CDevice.write(CONF1);
        //空读
        i2CDevice.write(READ);
        i2CDevice.read(temp, 0, 2);
        //正式读
        i2CDevice.write(READ);
        i2CDevice.read(temp, 0, 2);

//        System.out.println(temp[0] << 4);
//        System.out.println(temp[1] >> 4);
        int res = (byte2short(temp) >>> 4);
        double voltage = (double) res / 2047 * 6.144;
//        System.out.println( "电压为: " + voltage);

        //目前采用的振动传感器量程为0-10mm/s,模拟量输出为1-5V，参考电压为5V
        double vibration = (voltage  - 1) * 2.5;

        //过滤低于0.01的值
        if (vibration < 0.001) {
            vibration = 0;
        }
        return vibration;
    }
}
